<template>
  <!-- 用户导入对话框 -->
  <el-dialog :title="upload.title" v-model="isShow" width="400px" append-to-body>
    <el-upload
      ref="uploadEl"
      :limit="1"
      accept=".xlsx, .xls"
      :headers="{ Authorization: 'Bearer ' + getToken() }"
      :action="upload.url + '?updateSupport=' + upload.updateSupport"
      :disabled="isUploading"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :auto-upload="false"
      drag
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip" >
          <el-button
            type="primary"
            plain
            icon="el-icon-download"
            size="mini"
            @click="downloadTemplate"
          >下载模板</el-button>
          <div style="color:red">
            提示：仅允许导入“xls”或“xlsx”格式文件！
          </div>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts">
import { defineComponent, watch, ref } from 'vue'
import { getToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'
import { downloadResource } from '@/utils'
export default defineComponent({
  name: 'UploadDialog',
  emits: ['onRefresh', 'close'],
  props: {
    upload: {
      type: Object,
      default: () => {
        return {}
      }
    },
    value: {
      type: Boolean,
      default: false
    }
  },
  setup(props, context) {
    // const store = useStore()
    const isUploading = ref<boolean>(false)
    const uploadEl = ref<HTMLElement>()
    const isShow = ref<boolean>(false)
    const close = () => {
      isShow.value = false
      context.emit('close', false)
    }

    const downloadTemplate = () => {
      downloadResource(props.upload.templateUrl)
    }
    // 文件上传中处理
    const handleFileUploadProgress = () => {
      isUploading.value = true
    }
    const handleFileSuccess = () => {
      isUploading.value = false
      uploadEl.value && (uploadEl.value as any).clearFiles()
      ElMessage({
        message: '上传成功',
        type: 'success'
      })
      close()
    }
    const submitFileForm = () => {
      uploadEl.value && (uploadEl.value as any).submit()
    }
    watch(() => props.upload.open, (val) => {
      isShow.value = val
    })
    return {
      uploadEl,
      close,
      isShow,
      getToken,
      downloadTemplate,
      handleFileSuccess,
      handleFileUploadProgress,
      submitFileForm,
      isUploading
    }
  }
})
</script>
